package net.tycmc.cty.ctyms.timejob.bean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tycmc.functions.util.StringUtil;

import net.tycmc.bulb.common.util.MapGetter;
/**
 *载重段 对象
 *@author haoyang 
 */
public class LoadLine {
	/**
	 * 载重段的源数据（定时表）
	 * 油耗:oilCons，载重:load，行驶里程:runKm，行驶时间:runTime，信息时间:MsgTime，是否停留点:ifDisPoint
	 */
	private List<Map<String,Object>> loadSrcList = new ArrayList<Map<String,Object>>();
	
	/**
	 * 载重段位置源数据（位置表）
	 */
	private List<Map<String,Object>> pstnSrcList = new ArrayList<Map<String,Object>>();
	/**
	 * 载重区间
	 * 空载:noLoadBgn-noLoadEnd
	 * 装载:zhuangLoadBgn-zhuangLoadEnd
	 * 满载:fullLoadBgn-fullLoadEnd
	 * 特满载:teLoadBgn-teLoadEnd
	 * 无效区间:invalidBgn-invalidEnd
	 */
	private Map<String,Double> loadInterval = new HashMap<String, Double>();
	/**
	 * 载重调整系数
	 * 载重 = 原始载重 * x + y
	 * 乘数:x
	 * 加数:y
	 */
	private Map<String,Double> loadFactor = new HashMap<String, Double>();
	/**
	 * 计算该载重段内的平均载重（原始载重）
	 * @return
	 */
	private Map<String,Double> loadRange = null;//有效，无效载重区间
	
	//private double avgLoad = 0;//平均载重
	//private double avgLoadAft = 0;//平均载重（调整后）
	private double avgLoad = -1;//平均载重 jiyongtian20131106 默认值为-1
	private double avgLoadAft = -1;//平均载重（调整后）
	private String loadType = null;//载重类型
	
	public double getAvgLoad(){
//		if(avgLoad!=0)jiyongtian20131106 更新判断条件为大于0
		if(avgLoad > 0)
			return avgLoad;
		double load = 0;
		int num = 0;
		String currLoadStr;
		try {
			for(int i=0,len=loadSrcList.size();i<len;i++){
				currLoadStr = MapGetter.getString(loadSrcList.get(i), "load");
				if(StringUtil.isNullOrEmpty(currLoadStr)&&currLoadStr.matches("\\d+(\\.\\d+)?")){
					double currLoad= Double.parseDouble(currLoadStr);
					if(isValidLoad(currLoad)){
						load += currLoad;
						num++;
					}
				}
			}
		} catch (NumberFormatException e) {
		}
		currLoadStr = null;
		if(num==0){
			
		}else{
			avgLoad = load/(num==0?1:num);
		}
		return avgLoad;
	}
	/**
	 * 计算该载重段内的载重（调整后载重）
	 * @return
	 */
	public double getAvgLoadAft(){
		//if(avgLoadAft!=0)jiyongtian20131106 更新判断条件为大于0
		if(avgLoadAft > 0)
			return avgLoadAft;
		double x,y;
		x =  MapGetter.getDouble(getLoadFactor(), "x");
		y =  MapGetter.getDouble(getLoadFactor(), "y");
		double load = getAvgLoad();
		if(load >=0){
			avgLoadAft = load*x+y;
		}else{
			
		}
		return avgLoadAft;
	}
	/**
	 * 根据参数名称，获取相应 计算结果
	 * @param paramName：
	 * 	runKm：行驶公里
	 * runTime：行驶小时
	 * oilCons：油耗
	 * load：调整后平均载重
	 * TKM：吨公里
	 * U：单耗
	 * oilRate：油耗率
	 * @return
	 */
	public double getValueByParamName(String paramName){
		if("runKm".equalsIgnoreCase(paramName)){
			return getChaZhi("runKm");
		}else if("MsgT_tRunKmExact".equalsIgnoreCase(paramName)){
			return getChaZhi("MsgT_tRunKmExact");
		}else if("MsgT_tRunKm".equalsIgnoreCase(paramName)){
			return getChaZhi("MsgT_tRunKm");
		}else if("MsgT_tRunKmECU".equalsIgnoreCase(paramName)){
			return getChaZhi("MsgT_tRunKmECU");
		}else if("MsgT_tRunKmExact_PGN".equalsIgnoreCase(paramName)){
			return getChaZhi("MsgT_tRunKmExact_PGN");
		}else if("VclP_Tmileage".equalsIgnoreCase(paramName)){
			return getChaZhi("VclP_Tmileage");
		}else if("runTime".equalsIgnoreCase(paramName)){
			return getChaZhi("runTime");
		}else if("oilCons".equalsIgnoreCase(paramName)){
			return getChaZhi("oilCons");
		}else if("load".equalsIgnoreCase(paramName)){
			return getAvgLoadAft();
		}else if("TKM".equalsIgnoreCase(paramName)){
			double TKM = 0;
			double runKm = getValueByParamName("runKm");
			double load = getAvgLoadAft();
			if(load>=0&&runKm>=0)
				TKM = runKm*load/1000;
			return TKM;
		}else if("U".equalsIgnoreCase(paramName)){
			double U = 0;
			double TKM = getValueByParamName("TKM");
			double oilCons = getChaZhi("oilCons");
			if(TKM>0&&oilCons>=0)
				U = oilCons/TKM;
			return U;
		}else if("oilRate".equalsIgnoreCase(paramName)){
			double totalOil = getValueByParamName("oilCons");
			double runKm = getValueByParamName("runKm");
			if(totalOil>=0&&runKm>0)
				return totalOil/runKm*100;
			return 0;
		}
		
		return 0;
	}
	
	/**
	 * 获取该载重段 有效的信息时间差（最后一条-第一条）
	 * @return
	 */
	public double getMsgTimeCha(){
		Map<String,Object> time = getFirstAndLastValidValue("MsgTime");
		String bgnTime = MapGetter.getString(time, "firstValue");
		String endTime = MapGetter.getString(time, "lastValue");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		int min = 0;
		try {
			min = (int)(sdf.parse(endTime).getTime()-sdf.parse(bgnTime).getTime())/1000/60;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		time = null;
		bgnTime = null;
		endTime = null;
		sdf = null;
		return min;
	}
	/**
	 * 载重段 相加——定时信息和位置信息
	 * 如果当前对象定时信息、位置信息为null，则执行赋值操作
	 * @param loadLine
	 * @return
	 */
	public LoadLine add(LoadLine loadLine){
		//位置信息相加
		this.addPstnSrcList(loadLine);
		if(loadLine.getLoadSrcList().size()==0){
			return this;
		}
		if(loadSrcList.size()==0){
			loadSrcList.addAll(loadLine.getLoadSrcList());
			return this;
		}
		//1.当前段 最后一个点
		Map<String,Object> lastP = loadSrcList.get(loadSrcList.size()-1);
		//2.添加段 第一个点
		Map<String,Object> firstP = loadLine.getLoadSrcList().get(0);
		//if(lastP.equals(firstP)){
		if(this.equalsOfTimingAndPstnMap(lastP,firstP,"MsgT_ID")){
			loadSrcList.addAll(loadLine.getLoadSrcList().subList(1,loadLine.getLoadSrcList().size() ));
		}else{
			loadSrcList.addAll(loadLine.getLoadSrcList());
		}
		lastP = null;
		firstP = null;
		return this;
	}
	private void addPstnSrcList(LoadLine loadLine){
		if(loadLine.getPstnSrcList().size()==0)
			return;
		if(pstnSrcList.size()==0){
			pstnSrcList.addAll(loadLine.getPstnSrcList());
			return;
		}
		//1.当前段 最后一个点
		Map<String,Object> lastP = pstnSrcList.get(pstnSrcList.size()-1);
		//2.添加段 第一个点
		Map<String,Object> firstP = loadLine.getPstnSrcList().get(0);
		//if(lastP.equals(firstP)){
		if(this.equalsOfTimingAndPstnMap(lastP,firstP,null)){
			pstnSrcList.addAll(loadLine.getPstnSrcList().subList(1,loadLine.getPstnSrcList().size() ));
		}else{
			pstnSrcList.addAll(loadLine.getPstnSrcList());
		}
		lastP = null;
		firstP = null;
		return;
	}
	private boolean equalsOfTimingAndPstnMap(Map<String,Object> oneMap,Map<String,Object> otherMap,String Key){
		boolean flag = false;
		if(null!= Key && StringUtil.isValid(Key)){
			if(StringUtil.isValid(MapGetter.getString(oneMap, Key))&&StringUtil.isValid(MapGetter.getString(otherMap, Key))
					&&(MapGetter.getString(otherMap, Key).compareTo(MapGetter.getString(otherMap, Key))==0)){
				flag = true;
			}
		}else{
			if(StringUtil.isValid(MapGetter.getString(oneMap, "VclP_ID"))&&StringUtil.isValid(MapGetter.getString(otherMap, "VclP_ID"))
					  &&(MapGetter.getString(otherMap, "VclP_ID").compareTo(MapGetter.getString(otherMap, "VclP_ID"))==0)){
				flag = true;
			}else{
				if(StringUtil.isValid(MapGetter.getString(oneMap, "MsgT_ID"))&&StringUtil.isValid(MapGetter.getString(otherMap, "MsgT_ID"))
						  &&(MapGetter.getString(otherMap, "MsgT_ID").compareTo(MapGetter.getString(otherMap, "MsgT_ID"))==0)){
					flag = true;
				}
			}
		}
		return flag;
	}
	/**
	 * 计算该载重段内 相应参数的差值(最后一条和第一条 有效值之差)
	 * @param valueName
	 * @return
	 */
	private double getChaZhi(String valueName){
		Map<String,Object> km = getFirstAndLastValidValue(valueName);
		if("noData".equals(MapGetter.getString(km, "firstValue")))
			return 0;
		double result = Double.parseDouble(MapGetter.getString(km, "lastValue"))-
				Double.parseDouble(MapGetter.getString(km, "firstValue"));
		return result>0?result:0;
	}
	
	
	/**
	 * 获取 第一个，最后一个 有效的值（做差运算时使用）
	 * @param valueName
	 * @return firstValue,lastValue
	 */

	private Map<String,Object> getFirstAndLastValidValue(String valueName){
		Map<String,Object> retValue = new HashMap<String, Object>();
		String first = "noData";
		String last = "noData";
		for (Map<String,Object> curr : loadSrcList) {
			if(StringUtil.isNullOrEmpty(MapGetter.getString(curr, valueName))){
				first = MapGetter.getString(curr, valueName);
				break;
			}
		}
		for(int i=loadSrcList.size()-1;i>=0;i--){
			if(StringUtil.isNullOrEmpty(MapGetter.getString(loadSrcList.get(i), valueName))){
				last = MapGetter.getString(loadSrcList.get(i), valueName);
				break;
			}
		}
		retValue.put("firstValue",first);
		retValue.put("lastValue",last);
		first = null;
		last = null;
		return retValue;
	}
	/**
	 * 判断 载重 是否为 有效载重
	 * @param load
	 * @return
	 */
	private boolean isValidLoad(double load){
		if(loadRange==null)
			loadRange = getLoadRange();
		double validBgn = Double.parseDouble(MapGetter.getString(loadRange, "validBgn"));
		double validEnd = Double.parseDouble(MapGetter.getString(loadRange, "validEnd"));
		double invalidBgn = Double.parseDouble(MapGetter.getString(loadRange, "invalidBgn"));
		double invalidEnd = Double.parseDouble(MapGetter.getString(loadRange, "invalidEnd"));
		return (load>=validBgn&&load<=validEnd&&(load<invalidBgn||load>invalidEnd));
	}
	/**
	 * 获取载重有效，无效区间
	 * @return
	 */
	private Map<String,Double> getLoadRange(){
		double noLoadBgn = MapGetter.getDouble(loadInterval, "noLoadBgn");
		double noLoadEnd = MapGetter.getDouble(loadInterval, "noLoadEnd");
		double zhuangLoadBgn = MapGetter.getDouble(loadInterval, "zhuangLoadBgn");
		double zhuangLoadEnd = MapGetter.getDouble(loadInterval, "zhuangLoadEnd");
		double fullLoadBgn = MapGetter.getDouble(loadInterval, "fullLoadBgn");
		double fullLoadEnd = MapGetter.getDouble(loadInterval, "fullLoadEnd");
		double teLoadBgn = MapGetter.getDouble(loadInterval, "teLoadBgn");
		double teLoadEnd = MapGetter.getDouble(loadInterval, "teLoadEnd");
		double invalidBgn = MapGetter.getDouble(loadInterval, "invalidBgn");
		double invalidEnd = MapGetter.getDouble(loadInterval, "invalidEnd");
		List<Double> interval = new ArrayList<Double>(8);
		interval.add(noLoadBgn);
		interval.add(noLoadEnd);
		interval.add(zhuangLoadBgn);
		interval.add(zhuangLoadEnd);
		interval.add(fullLoadBgn);
		interval.add(fullLoadEnd);
		interval.add(teLoadBgn);
		interval.add(teLoadEnd);
		Collections.sort(interval);
		Map<String,Double> retValue = new HashMap<String, Double>();
		retValue.put("validBgn", interval.get(0));
		retValue.put("validEnd", interval.get(7));
		retValue.put("invalidBgn", invalidBgn);
		retValue.put("invalidEnd", invalidEnd);
		interval = null;
		return retValue;
	}
	
	/**
	 * 判断 该段数据所处的运行状态
	 * @param srcList
	 * @return true：运行，false：停止
	 */
	public boolean isRunning(){
		for (Map<String, Object> map : loadSrcList) {
			if(MapGetter.getString(map, "ifDisPoint").equals("0"))
				return true;
		}
		return false;
	}
	
	public final List<Map<String, Object>> getLoadSrcList() {
		return loadSrcList;
	}
	public final void setLoadSrcList(List<Map<String, Object>> loadSrcList) {
		this.loadSrcList = loadSrcList;
	}
	/**
	 * 该载重段的载重类型(0:未知或其他，1：空载，2：装载，3：满载，4：特满载)
	 */
	public String getLoadType() {
		if(StringUtil.isNullOrEmpty(loadType))
			return loadType;
		double avgLoadAft = getAvgLoadAft();
		double noLoadBgn = MapGetter.getDouble(loadInterval, "noLoadBgn");
		double noLoadEnd = MapGetter.getDouble(loadInterval, "noLoadEnd");
		double zhuangLoadBgn = MapGetter.getDouble(loadInterval, "zhuangLoadBgn");
		double zhuangLoadEnd = MapGetter.getDouble(loadInterval, "zhuangLoadEnd");
		double fullLoadBgn = MapGetter.getDouble(loadInterval, "fullLoadBgn");
		double fullLoadEnd = MapGetter.getDouble(loadInterval, "fullLoadEnd");
		double teLoadBgn = MapGetter.getDouble(loadInterval, "teLoadBgn");
		double teLoadEnd = MapGetter.getDouble(loadInterval, "teLoadEnd");
/*		if(avgLoadAft>=noLoadBgn&&avgLoadAft<=noLoadEnd){
			loadType = "1";
		}else if(avgLoadAft>=zhuangLoadBgn&&avgLoadAft<=zhuangLoadEnd){
			loadType = "2";
		}else if(avgLoadAft>=fullLoadBgn&&avgLoadAft<=fullLoadEnd){
			loadType = "3";
		}else if(avgLoadAft>=teLoadBgn&&avgLoadAft<=teLoadEnd){
			loadType = "4";
		}else{
			loadType = "0";
		}*/
		//jiyongtian增加默认值的判断
		if(avgLoadAft>=0){
			if(avgLoadAft>=noLoadBgn&&avgLoadAft<=noLoadEnd){
				loadType = "1";
			}else if(avgLoadAft>=zhuangLoadBgn&&avgLoadAft<=zhuangLoadEnd){
				loadType = "2";
			}else if(avgLoadAft>=fullLoadBgn&&avgLoadAft<=fullLoadEnd){
				loadType = "3";
			}else if(avgLoadAft>=teLoadBgn&&avgLoadAft<=teLoadEnd){
				loadType = "4";
			}else{
				loadType = "0";
			}
		}else{
			loadType = "0";
		}
		return loadType;
	}
	public String getLoadTypeName() {
		String type = getLoadType();
		return type.equals("1")?"空载":
					type.equals("2")?"装载":
					type.equals("3")?"满载":
					type.equals("4")?"特满载":"其他";
	}
	public Map<String, Double> getLoadInterval() {
		return loadInterval;
	}
	public void setLoadInterval(Map<String, Double> loadInterval) {
		this.loadInterval = loadInterval;
	}
	public Map<String, Double> getLoadFactor() {
		if(!StringUtil.isNullOrEmpty(MapGetter.getString(loadFactor, "x"))){
			loadFactor.put("x", 1.0);
		}
		if(!StringUtil.isNullOrEmpty(MapGetter.getString(loadFactor, "y"))){
			loadFactor.put("y", 0.0);
		}
		return loadFactor;
	}
	public void setLoadFactor(Map<String, Double> loadFactor) {
		this.loadFactor = loadFactor;
	}
	public List<Map<String, Object>> getPstnSrcList() {
		return pstnSrcList;
	}
	public void setPstnSrcList(List<Map<String, Object>> pstnSrcList) {
		this.pstnSrcList = pstnSrcList;
	}
	
}